﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace PKEngine
{
	/// <summary>
	/// Delegate for scheduler.
	/// </summary>
	public delegate void SchedulerDelegate(float dt);

	/// <summary>
	/// Interface for updateable object.
	/// </summary>
	public interface IPKUpdate
	{
		void Update(float dt);
	}

	/// <summary>
	/// Scheduler is used for triggering the scheduled callbacks.
	/// </summary>
	public class PKScheduler
	{
		#region PKTimer
		/// <summary>
		/// Light weight timer.
		/// </summary>
		private class PKTimer : IPKUpdate
		{
			#region Public Properties
			public SchedulerDelegate TargetDelegate { get; set; }
			public float Interval { get; set; }
			public float Elapsed { get; private set; }
			public bool RunForever { get; private set; }
			public bool UseDelay { get; private set; }
			public int TimesExecuted { get; private set; }
			public int Repeat { get; private set; } //0 = once, 1 = twice, ...
			public float Delay { get; private set; }
			#endregion

			#region Initialization
			public PKTimer(SchedulerDelegate targetDelegate, float interval, int repeat, float delay)
			{
				this.Interval = interval;
				this.Elapsed = -1;
				this.Delay = delay;
				this.UseDelay = delay > 0 ? true : false;
				this.Repeat = repeat;
				this.RunForever = repeat == -1 ? true : false;
				this.TargetDelegate = targetDelegate;
			}
			#endregion

			#region Public Methods
			public void Update(float dt)
			{
				if (Elapsed == -1)
				{
					Elapsed = 0;
					TimesExecuted = 0;
				}
				else
				{
					if (RunForever && !UseDelay)
					{
						// standard timer usage
						Elapsed += dt;
						if (Elapsed >= Interval)
						{
							TargetDelegate(Elapsed);
							Elapsed = 0;
						}
					}
					else
					{
						// advanced usage
						Elapsed += dt;
						if (UseDelay)
						{
							if (Elapsed >= Delay)
							{
								TargetDelegate(0);
								Elapsed -= Delay;
								TimesExecuted += 1;
								UseDelay = false;
							}
						}
						else
						{
							if (Elapsed >= Interval)
							{
								TargetDelegate(Elapsed);
								Elapsed = 0;
								TimesExecuted++;
							}
						}

						if (!RunForever && TimesExecuted > Repeat)
						{
							PKScheduler.SharedScheduler.UnscheduleDelegateForTarget(TargetDelegate.Target, TargetDelegate);
						}
					}
				}
			}
			#endregion
		}
		#endregion

		#region UpdateListItem
		/// <summary>
		/// Items of update list.
		/// </summary>
		private class UpdateListItem
		{
			public IPKUpdate Target { get; set; }
			public int Priority { get; set; }
			public bool IsPaused { get; set; }

			public UpdateListItem(IPKUpdate target, int priority, bool isPaused)
			{
				this.Target = target;
				this.Priority = priority;
				this.IsPaused = isPaused;
			}
		}
		#endregion

		#region DelegateListItem
		/// <summary>
		/// Items of delagate list.
		/// </summary>
		private class DelegateListItem
		{
			public object Target { get; set; }
			public List<PKTimer> TimerList { get; set; }
			public int TimerIndex { get; set; }
			public bool IsPaused { get; set; }

			public DelegateListItem(object target, bool isPaused)
			{
				this.Target = target;
				this.TimerList = new List<PKTimer>();
				this.TimerIndex = -1;
				this.IsPaused = isPaused;
			}
		}
		#endregion

		#region Singleton
		private static PKScheduler _sharedScheduler;

		public static PKScheduler SharedScheduler
		{
			get
			{
				if (_sharedScheduler == null)
				{
					_sharedScheduler = new PKScheduler();
				}
				return _sharedScheduler;
			}
		}
		#endregion

		#region Private Fields
		private List<UpdateListItem> updateNegList;
		private List<UpdateListItem> updateZeroList;
		private List<UpdateListItem> updatePosList;
		private List<DelegateListItem> delegateList;
		private int updateNegIndex;
		private int updateZeroIndex;
		private int updatePosIndex;
		private int delegateIndex;
		#endregion

		#region Public Properties
		public float TimeScale { get; set; }
		#endregion

		#region Initialization
		private PKScheduler()
		{
			this.TimeScale = 1.0f;

			this.updateNegList = new List<UpdateListItem>();
			this.updateZeroList = new List<UpdateListItem>();
			this.updatePosList = new List<UpdateListItem>();
			this.delegateList = new List<DelegateListItem>();
			this.updateNegIndex = -1;
			this.updateZeroIndex = -1;
			this.updatePosIndex = -1;
			this.delegateIndex = -1;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Scheduled the update method for a target.
		/// If you have scheduled update for a target already, please unschedule
		/// update for it, then schedule update for it again.
		/// </summary>
		/// <param name="target">Target IUpdateableObject</param>
		/// <param name="priority">The priority of schedule</param>
		/// <param name="isPaused">If the schedule should be paused</param>
		public void ScheduleUpdateForTarget(IPKUpdate target, int priority, bool isPaused)
		{
			Debug.Assert(target != null, "Argument cannot be null.");
#if DEBUG
			// Make sure the target was not added before.
			// It will cost some time, so only do it in debug mode.
			Debug.Assert(PKScheduler.FindIndexOfUpdateListItemHelper(updateZeroList, target) == -1, "PKScheduler.ScheduleUpdateForTarget: Cannot schedule the update for target if it has been scheduled.");
			Debug.Assert(PKScheduler.FindIndexOfUpdateListItemHelper(updateNegList, target) == -1, "PKScheduler.ScheduleUpdateForTarget: Cannot schedule the update for target if it has been scheduled.");
			Debug.Assert(PKScheduler.FindIndexOfUpdateListItemHelper(updatePosList, target) == -1, "PKScheduler.ScheduleUpdateForTarget: Cannot schedule the update for target if it has been scheduled.");
#endif

			if (priority == 0)
			{
				PKScheduler.AddUpdateListItemHelper(updateZeroList, target, isPaused);
			}
			else if (priority < 0)
			{
				PKScheduler.InsertUpdateListItemHelper(updateNegList, ref updateNegIndex, target, priority, isPaused);
			}
			else
			{
				PKScheduler.InsertUpdateListItemHelper(updatePosList, ref updatePosIndex, target, priority, isPaused);
			}
		}

		/// <summary>
		/// Unscheduled the update method for a target.
		/// </summary>
		/// <param name="target">Target IUpdateableObject</param>
		public void UnscheduleUpdateForTarget(IPKUpdate target)
		{
			if (target == null)
			{
				return;
			}

			int index;
			index = PKScheduler.FindIndexOfUpdateListItemHelper(updateZeroList, target);
			if (index >= 0)
			{
				if (updateZeroIndex != -1 && index <= updateZeroIndex)
				{
					updateZeroIndex--;
				}
				updateZeroList.RemoveAt(index);
				return;
			}
			index = PKScheduler.FindIndexOfUpdateListItemHelper(updateNegList, target);
			if (index >= 0)
			{
				if (updateNegIndex != -1 && index <= updateNegIndex)
				{
					updateNegIndex--;
				}
				updateNegList.RemoveAt(index);
				return;
			}
			index = PKScheduler.FindIndexOfUpdateListItemHelper(updatePosList, target);
			if (index >= 0)
			{
				if (updateZeroIndex != -1 && index <= updateZeroIndex)
				{
					updateZeroIndex--;
				}
				updatePosList.RemoveAt(index);
				return;
			}
		}

		/// <summary>
		/// Scheduled delegate for a target.
		/// If you have scheduled delegate for a target already, please unschedule
		/// the delegate for it, then schedule the delegate for it again.
		/// </summary>
		/// <param name="target">Target object</param>
		/// <param name="sDelegate">Target delegate</param>
		/// <param name="sDelegate">The interval of schedule</param>
		/// <param name="isPaused">If the schedule should be paused</param>
		public void ScheduleDelegateForTarget(object target, SchedulerDelegate sDelegate, float interval, bool isPaused)
		{
			this.ScheduleDelegateForTarget(target, sDelegate, interval, isPaused, -1, 0);
		}

		/// <summary>
		/// Scheduled delegate for a target.
		/// If you have scheduled delegate for a target already, please unschedule
		/// the delegate for it, then schedule the delegate for it again.
		/// </summary>
		/// <param name="target">Target object</param>
		/// <param name="sDelegate">Target delegate</param>
		/// <param name="sDelegate">The interval of schedule</param>
		/// <param name="isPaused">If the schedule should be paused</param>
		/// <param name="repeat">-1: repeat forever, 0: once, 1: twice, ...</param>
		/// <param name="delay">schedule will start after delay</param>
		public void ScheduleDelegateForTarget(object target, SchedulerDelegate sDelegate, float interval, bool isPaused, int repeat, float delay)
		{
			Debug.Assert(target != null, "PKScheduler.ScheduleDelegateForTarget: Argument cannot be null.");
			Debug.Assert(sDelegate != null, "PKScheduler.ScheduleDelegateForTarget: Argument cannot be null.");

			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				Debug.Assert(item.IsPaused == isPaused, "PKScheduler.ScheduleDelegateForTarget: Trying to schedule a selector with a pause value different than the target.");
			}
			else
			{
				item = new DelegateListItem(target, isPaused);
				delegateList.Add(item);
			}

			PKTimer timer = PKScheduler.FindTimerHelper(item.TimerList, sDelegate);
			if (timer != null)
			{
				Debug.Print("PKScheduler.ScheduleDelegateForTarget: Selector already scheduled. Updating interval from {0} to {1}", timer.Interval.ToString("0.00"), interval.ToString("0.00"));
				timer.Interval = interval;
			}
			else
			{
				timer = new PKTimer(sDelegate, interval, repeat, delay);
				item.TimerList.Add(timer);
			}
		}

		/// <summary>
		/// Unscheduled delegate for a target.
		/// </summary>
		/// <param name="target">Target object</param>
		/// <param name="sDelegate">Target delegate</param>
		public void UnscheduleDelegateForTarget(object target, SchedulerDelegate sDelegate)
		{
			if (target == null || sDelegate == null)
			{
				return;
			}

			Debug.Assert(target != null, "PKScheduler.UnscheduleDelegateForTarget: Argument cannot be null.");
			Debug.Assert(sDelegate != null, "PKScheduler.UnscheduleDelegateForTarget: Argument cannot be null.");

			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				int timerIndex = PKScheduler.FindIndexOfTimerHelper(item.TimerList, sDelegate);
				if (timerIndex != -1)
				{
					if (item.TimerIndex != -1 && timerIndex <= item.TimerIndex)
					{
						item.TimerIndex--;
					}
					item.TimerList.RemoveAt(timerIndex);
					if (item.TimerList.Count == 0)
					{
						this.UnscheduleAllDelegatesForTargetHelper(target);
					}
				}
			}
		}

		/// <summary>
		/// Unscheduled all shedules for the target.
		/// </summary>
		/// <param name="target">Target object</param>
		public void UnscheduleAllSchedulesForTarget(object target)
		{
			if (target == null)
			{
				return;
			}

			// Delegate schedules
			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				this.UnscheduleAllDelegatesForTargetHelper(target);
			}

			// Update schedules
			IPKUpdate updateableObject = target as IPKUpdate;
			if (updateableObject != null)
			{
				this.UnscheduleUpdateForTarget(updateableObject);
			}
		}

		/// <summary>
		/// Unscheduled all shedules.
		/// </summary>
		public void UnscheduleAllSchedules()
		{
			foreach (DelegateListItem item in delegateList)
			{
				item.TimerList.Clear();
			}
			delegateList.Clear();
			updateZeroList.Clear();
			updateNegList.Clear();
			updatePosList.Clear();
		}

		/// <summary>
		/// Pause a target.
		/// </summary>
		/// <param name="target">Target object</param>
		public void PauseTarget(object target)
		{
			Debug.Assert(target != null, "PKScheduler.PauseTarget: Argument cannot be null.");

			// Delegate schedules
			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				item.IsPaused = true;
			}

			// Update schedules
			IPKUpdate updateableObject = target as IPKUpdate;
			if (updateableObject != null)
			{
				int index;
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateZeroList, updateableObject);
				if (index >= 0)
				{
					updateZeroList[index].IsPaused = true;
					return;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateNegList, updateableObject);
				if (index >= 0)
				{
					updateNegList[index].IsPaused = true;
					return;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updatePosList, updateableObject);
				if (index >= 0)
				{
					updatePosList[index].IsPaused = true;
					return;
				}
			}
		}

		/// <summary>
		/// Resume a target.
		/// </summary>
		/// <param name="target">Target object</param>
		public void ResumeTarget(object target)
		{
			Debug.Assert(target != null, "PKScheduler.ResumeTarget: Argument cannot be null.");

			// Delegate schedules
			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				item.IsPaused = false;
			}

			// Update schedules
			IPKUpdate updateableObject = target as IPKUpdate;
			if (updateableObject != null)
			{
				int index;
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateZeroList, updateableObject);
				if (index >= 0)
				{
					updateZeroList[index].IsPaused = false;
					return;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateNegList, updateableObject);
				if (index >= 0)
				{
					updateNegList[index].IsPaused = false;
					return;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updatePosList, updateableObject);
				if (index >= 0)
				{
					updatePosList[index].IsPaused = false;
					return;
				}
			}
		}

		/// <summary>
		/// If a target is paused.
		/// </summary>
		/// <param name="target">Target object</param>
		/// <returns>If it's paused</returns>
		public bool IsTargetPaused(object target)
		{
			Debug.Assert(target != null, "PKScheduler.IsTargetPaused: Argument cannot be null.");

			// Delegate schedules
			DelegateListItem item = PKScheduler.FindDelegateListItemHelper(delegateList, target);
			if (item != null)
			{
				return item.IsPaused;
			}

			// Update schedules
			IPKUpdate updateableObject = target as IPKUpdate;
			if (updateableObject != null)
			{
				int index;
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateZeroList, updateableObject);
				if (index >= 0)
				{
					return updateZeroList[index].IsPaused;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updateNegList, updateableObject);
				if (index >= 0)
				{
					return updateNegList[index].IsPaused;
				}
				index = PKScheduler.FindIndexOfUpdateListItemHelper(updatePosList, updateableObject);
				if (index >= 0)
				{
					return updatePosList[index].IsPaused;
				}
			}

			// Should never get here.
			return true;
		}

		/// <summary>
		/// Pause all schedules for all running targets.
		/// </summary>
		/// <returns>Paused targets</returns>
		public List<object> PauseAllRunningTargets()
		{
			List<object> pausedTargets = new List<object>();
			foreach (DelegateListItem item in delegateList)
			{
				item.IsPaused = true;
				pausedTargets.Add(item.Target);
			}
			foreach (UpdateListItem item in updateZeroList)
			{
				item.IsPaused = true;
				if (!pausedTargets.Contains(item.Target))
				{
					pausedTargets.Add(item.Target);
				}
			}
			foreach (UpdateListItem item in updateNegList)
			{
				item.IsPaused = true;
				if (!pausedTargets.Contains(item.Target))
				{
					pausedTargets.Add(item.Target);
				}
			}
			foreach (UpdateListItem item in updatePosList)
			{
				item.IsPaused = true;
				if (!pausedTargets.Contains(item.Target))
				{
					pausedTargets.Add(item.Target);
				}
			}
			return pausedTargets;
		}

		/// <summary>
		/// Resume all schedules for a set of targets. (convenience function to reverse a PauseAllTarget call)
		/// </summary>
		/// <param name="targetsToResume">Targets to resume</param>
		public void ResumeTargets(List<object> targetsToResume)
		{
			foreach (object target in targetsToResume)
			{
				this.ResumeTarget(target);
			}
		}

		/// <summary>
		/// Update all schedules.
		/// It should be called by main loop.
		/// Do not call it manually, unless you know what you are doing.
		/// </summary>
		/// <param name="dt">Delta time</param>
		public void Update(float dt)
		{
			if (TimeScale != 1.0f)
			{
				dt *= TimeScale;
			}

			for (updateNegIndex = 0; updateNegIndex < updateNegList.Count; updateNegIndex++)
			{
				UpdateListItem updateListItem = updateNegList[updateNegIndex];
				if (!updateListItem.IsPaused)
				{
					updateListItem.Target.Update(dt);
				}
			}
			updateNegIndex = -1;

			for (updateZeroIndex = 0; updateZeroIndex < updateZeroList.Count; updateZeroIndex++)
			{
				UpdateListItem updateListItem = updateZeroList[updateZeroIndex];
				if (!updateListItem.IsPaused)
				{
					updateListItem.Target.Update(dt);
				}
			}
			updateZeroIndex = -1;

			for (updatePosIndex = 0; updatePosIndex < updatePosList.Count; updatePosIndex++)
			{
				UpdateListItem updateListItem = updatePosList[updatePosIndex];
				if (!updateListItem.IsPaused)
				{
					updateListItem.Target.Update(dt);
				}
			}
			updatePosIndex = -1;

			for (delegateIndex = 0; delegateIndex < delegateList.Count; delegateIndex++)
			{
				DelegateListItem delegateListItem = delegateList[delegateIndex];
				if (!delegateListItem.IsPaused)
				{
					for (delegateListItem.TimerIndex = 0; delegateListItem.TimerIndex < delegateListItem.TimerList.Count; delegateListItem.TimerIndex++)
					{
						PKTimer timer = delegateListItem.TimerList[delegateListItem.TimerIndex];
						timer.Update(dt);
					}
					delegateListItem.TimerIndex = -1;
				}
			}
			delegateIndex = -1;
		}
		#endregion

		#region Private Methods
		private static int FindIndexOfUpdateListItemHelper(List<UpdateListItem> list, IPKUpdate target)
		{
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Target == target)
				{
					return i;
				}
			}

			return -1;
		}

		private static void InsertUpdateListItemHelper(List<UpdateListItem> list, ref int currentIndex, IPKUpdate target, int priority, bool isPaused)
		{
			if (list.Count == 0 || priority >= list[list.Count - 1].Priority)
			{
				list.Add(new UpdateListItem(target, priority, isPaused));
			}
			else
			{
				for (int i = 0; i < list.Count; i++)
				{
					if (priority < list[i].Priority)
					{
						if (currentIndex != -1 && i <= currentIndex)
						{
							currentIndex++;
						}
						list.Insert(i, new UpdateListItem(target, priority, isPaused));
						break;
					}
				}
			}
		}

		private static void AddUpdateListItemHelper(List<UpdateListItem> list, IPKUpdate target, bool isPaused)
		{
			list.Add(new UpdateListItem(target, 0, isPaused));
		}

		private static DelegateListItem FindDelegateListItemHelper(List<DelegateListItem> list, object target)
		{
			foreach (DelegateListItem item in list)
			{
				if (item.Target == target)
				{
					return item;
				}
			}

			return null;
		}

		private static int FindIndexOfDelegateListItemHelper(List<DelegateListItem> list, object target)
		{
			for (int i = 0; i < list.Count; i++)
			{
				DelegateListItem item = list[i];
				if (item.Target == target)
				{
					return i;
				}
			}

			return -1;
		}

		private static PKTimer FindTimerHelper(List<PKTimer> list, SchedulerDelegate sDelegate)
		{
			foreach (PKTimer item in list)
			{
				if (item.TargetDelegate.Equals(sDelegate))
				{
					return item;
				}
			}

			return null;
		}

		private static int FindIndexOfTimerHelper(List<PKTimer> list, SchedulerDelegate sDelegate)
		{
			for (int i = 0; i < list.Count; i++)
			{
				PKTimer item = list[i];
				if (item.TargetDelegate.Equals(sDelegate))
				{
					return i;
				}
			}

			return -1;
		}

		private void UnscheduleAllDelegatesForTargetHelper(object target)
		{
			int targetIndex = PKScheduler.FindIndexOfDelegateListItemHelper(delegateList, target);
			if (targetIndex != -1)
			{
				if (delegateIndex != -1 && targetIndex <= delegateIndex)
				{
					delegateIndex--;
				}
				delegateList.RemoveAt(targetIndex);
			}
		}
		#endregion
	}
}